package com.ny.service.impl;

import com.ny.entity.Device;
import com.ny.mapper.DeviceRepository;
import com.ny.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private MongoTemplate mongoTemplate;  // 用于复杂查询和更新操作

    @Override
    public List<Device> findAllDevices() {
        return deviceRepository.findAll();
    }

    @Override
    public Device saveDevice(Device device) {
        // 设置创建时间（如果未设置）
        if (device.getCreated_time() == null) {
            device.setCreated_time(new Date());
        }
        return deviceRepository.save(device);
    }

    @Override
    public boolean deleteDeviceByDeviceId(Integer deviceId) {
        // 先查询是否存在该设备
        Query query = new Query(Criteria.where("device_id").is(deviceId));
        long count = mongoTemplate.count(query, Device.class);

        if (count > 0) {
            // 存在则删除
            mongoTemplate.remove(query, Device.class);
            return true;
        }
        return false;
    }

    @Override
    public Optional<Device> updateDeviceStatus(Integer deviceId, Integer status) {
        // 创建查询条件
        Query query = new Query(Criteria.where("device_id").is(deviceId));

        // 创建更新操作
        Update update = new Update();
        update.set("status", status);

        // 执行更新并返回更新后的文档
        Device updatedDevice = mongoTemplate.findAndModify(query, update, Device.class);

        return Optional.ofNullable(updatedDevice);
    }
}